﻿Imports System.Xml
Imports System.Xml.Schema
Imports System.IO
Imports System.Text
Imports System.Xml.Xsl
Imports System.Xml.XPath
Public Class csUtilsCFDI2
    'Public Function pedirTimbrado(ByVal guid As String, ByRef mensajeWebService As String, ByVal rutaWs As String) As String
    '    Dim timbre As String = ""
    '    Try
    '        Dim Web As commSifeiWS.csComunicacion = New commSifeiWS.csComunicacion(rutaWs)

    '        If (Web.obtenTimbrado(guid, timbre, mensajeWebService) = True) Then
    '            'clsConnSifei.writeLog("Timbrado Exitoso para el GUID: " & guid)
    '        Else
    '            timbre = Nothing

    '        End If
    '    Catch ex As Exception

    '    End Try
    '    Return timbre
    'End Function

    Public Sub integraAddendaCFD(ByRef pResMsg As String, ByRef xmlCfd As XmlDocument, ByVal addenda As XmlNode)
        Try
            Dim nodo As XmlNodeList
            nodo = xmlCfd.GetElementsByTagName("Comprobante")
            Dim add As XmlNode
            add = xmlCfd.ImportNode(addenda, True)
            nodo(0).AppendChild(add)
            Dim variable As String = xmlCfd.InnerXml
            Dim nuevavariable As String = variable.Replace("<Addenda xmlns="""">", "<Addenda>")
            xmlCfd.InnerXml = nuevavariable
        Catch ex As Exception
            pResMsg &= ex.Message & vbCrLf
        End Try
    End Sub
    Function IsTimbreValido(ByVal xml As String, ByVal ruta As String) As Boolean
        Dim schemaSet As New XmlSchemaSet
        Dim settings As New XmlReaderSettings
        Dim reader As XmlReader
        Dim nt As NameTable
        Dim nsmgr As XmlNamespaceManager
        Dim context As XmlParserContext
        Try
            schemaSet.Add("http://www.sat.gob.mx/TimbreFiscalDigital", _
                          XmlReader.Create(New StreamReader(ruta)))
            'clsConnSifei.ApplicationPath() & "\CFDI\Xsd\TimbreFiscalDigital.xsd"
            settings.Schemas = schemaSet
            settings.ValidationType = ValidationType.Schema

            nt = New NameTable()
            nsmgr = New XmlNamespaceManager(nt)
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
            context = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
            settings.ConformanceLevel = ConformanceLevel.Fragment

            reader = XmlReader.Create(New StringReader(xml), settings, context)
            While reader.Read
            End While
        Catch ex As Exception
            Throw New Exception("No se pudo validar el Timbre con las especificaciones del SAT: " & ex.Message.ToString)
        Finally
            settings = Nothing
            reader = Nothing
            schemaSet = Nothing
            nt = Nothing
            nsmgr = Nothing
            context = Nothing
        End Try
        Return True
    End Function
    'Function insertaTimbreEnBD(ByVal node As XmlNode, ByRef pResultMensaje As String, _
    '                           ByVal idFactura As Integer, ByVal Conexion As String) As Boolean
    '    Try
    '        Dim timbre As UtileriasBuzon.TimbreFiscalDigital = New UtileriasBuzon.TimbreFiscalDigital()
    '        timbre.selloCFD = node.Attributes.ItemOf("selloCFD").Value.ToString()
    '        timbre.selloSAT = node.Attributes.ItemOf("selloSAT").Value.ToString()
    '        timbre.FechaTimbrado = CDate(node.Attributes.ItemOf("FechaTimbrado").Value.ToString())
    '        timbre.noCertificadoSAT = node.Attributes.ItemOf("noCertificadoSAT").Value.ToString()
    '        timbre.UUID = node.Attributes.ItemOf("UUID").Value.ToString()
    '        timbre.version = node.Attributes.ItemOf("version").Value.ToString()

    '        Dim dalTimbre As UtileriasBuzon.timbreDAL = New UtileriasBuzon.timbreDAL()
    '        If (dalTimbre.registraTimbre(timbre, idFactura, Conexion) = True) Then
    '            Return True
    '        Else
    '            Return False
    '        End If
    '    Catch ex As Exception
    '        pResultMensaje = ex.Message
    '        Return False
    '    End Try

    'End Function
    'Function insertaTimbreEnBD(ByVal timbreXML As String, ByRef pResultMensaje As String, _
    '                           ByVal idFactura As Integer, ByVal pXmlCfdParc As XmlDocument, _
    '                           ByVal Conexion As String) As Boolean
    '    Try
    '        Dim nt As NameTable = New NameTable()
    '        Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
    '        nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
    '        Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
    '        Dim xset As XmlReaderSettings = New XmlReaderSettings()
    '        xset.ConformanceLevel = ConformanceLevel.Fragment
    '        Dim rd As XmlReader = XmlReader.Create(New StringReader(timbreXML), xset, context)
    '        Dim node As XmlNode = pXmlCfdParc.ReadNode(rd)

    '        Dim timbre As UtileriasBuzon.TimbreFiscalDigital = New UtileriasBuzon.TimbreFiscalDigital()
    '        timbre.selloCFD = node.Attributes.ItemOf("selloCFD").Value.ToString()
    '        timbre.selloSAT = node.Attributes.ItemOf("selloSAT").Value.ToString()
    '        timbre.FechaTimbrado = CDate(node.Attributes.ItemOf("FechaTimbrado").Value.ToString())
    '        timbre.noCertificadoSAT = node.Attributes.ItemOf("noCertificadoSAT").Value.ToString()
    '        timbre.UUID = node.Attributes.ItemOf("UUID").Value.ToString()
    '        timbre.version = node.Attributes.ItemOf("version").Value.ToString()

    '        Dim dalTimbre As UtileriasBuzon.timbreDAL = New UtileriasBuzon.timbreDAL()
    '        If (dalTimbre.registraTimbre(timbre, idFactura, Conexion) = True) Then
    '            Return True
    '        Else
    '            Return False
    '        End If
    '    Catch ex As Exception
    '        pResultMensaje = ex.Message
    '        Return False
    '    End Try

    'End Function
    'Function insertaTimbreEnBDRet(ByVal timbreXML As String, ByRef pResultMensaje As String, _
    '                           ByVal idRet As Integer, ByVal pXmlCfdParc As XmlDocument, _
    '                           ByVal Conexion As String) As Boolean
    '    Try
    '        Dim nt As NameTable = New NameTable()
    '        Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
    '        nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
    '        Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
    '        Dim xset As XmlReaderSettings = New XmlReaderSettings()
    '        xset.ConformanceLevel = ConformanceLevel.Fragment
    '        Dim rd As XmlReader = XmlReader.Create(New StringReader(timbreXML), xset, context)
    '        Dim node As XmlNode = pXmlCfdParc.ReadNode(rd)

    '        Dim timbre As UtileriasBuzon.TimbreFiscalDigital = New UtileriasBuzon.TimbreFiscalDigital()
    '        timbre.selloCFD = node.Attributes.ItemOf("selloCFD").Value.ToString()
    '        timbre.selloSAT = node.Attributes.ItemOf("selloSAT").Value.ToString()
    '        timbre.FechaTimbrado = CDate(node.Attributes.ItemOf("FechaTimbrado").Value.ToString())
    '        timbre.noCertificadoSAT = node.Attributes.ItemOf("noCertificadoSAT").Value.ToString()
    '        timbre.UUID = node.Attributes.ItemOf("UUID").Value.ToString()
    '        timbre.version = node.Attributes.ItemOf("version").Value.ToString()

    '        Dim dalTimbre As UtileriasBuzon.timbreDAL = New UtileriasBuzon.timbreDAL()
    '        If (dalTimbre.registraTimbreRet(timbre, idRet, Conexion) = True) Then
    '            Return True
    '        Else
    '            Return False
    '        End If
    '    Catch ex As Exception
    '        pResultMensaje = ex.Message
    '        Return False
    '    End Try

    'End Function

    Public Sub integraAddenda(ByRef pResMsg As String, ByRef xmlCfdi As XmlDocument, ByVal addenda As String)


        Dim xmlnsManager As XmlNamespaceManager
        Try

            addenda = addenda.Replace("<cfdi:Addenda xmlns:cfdi=""http://www.sat.gob.mx/cfd/3"">", "<cfdi:Addenda>")

            xmlnsManager = New XmlNamespaceManager(xmlCfdi.NameTable)
            'Agregamos los namespaces 
            xmlnsManager.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3")
            xmlnsManager.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
            xmlnsManager.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")


            'Valida sellos iguales

            Dim root As XmlNode = xmlCfdi.DocumentElement
            'Verificamos que el nodo Complementos exista
            Dim nodoCompl As XmlNode = root.SelectSingleNode("cfdi:Complemento", xmlnsManager)
            If (nodoCompl Is Nothing) Then
                'El nodo Complemento no existe, hay que crearlo
                nodoCompl = xmlCfdi.CreateNode(XmlNodeType.Element, "cfdi", "Complemento", "http://www.sat.gob.mx/cfd/3")
                root.AppendChild(nodoCompl)
            End If

            Dim nt As NameTable = New NameTable()
            Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
            nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3")
            Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
            Dim xset As XmlReaderSettings = New XmlReaderSettings()
            xset.ConformanceLevel = ConformanceLevel.Fragment
            Dim rd As XmlReader = XmlReader.Create(New StringReader(addenda), xset, context)
            Dim node As XmlNode = xmlCfdi.ReadNode(rd)

            '                        nodoCompl.AppendChild(node)
            root.AppendChild(node)
            
        Catch ex As Exception
            pResMsg &= ex.Message & vbCrLf
        End Try
    End Sub
    'Public Function integraTimbre(ByVal timbre As String, ByVal rutaEntrada As String, _
    '                              ByVal archivoIdCFDI As String, ByRef pResMsg As String, _
    '                              ByVal addenda As String, ByVal Conexion As String, Optional ByVal insertaTimbre As Boolean = True) As XmlDocument
    '    Dim xmlCfdi As XmlDocument = New XmlDocument()

    '    Dim xmlnsManager As XmlNamespaceManager
    '    Try

    '        Dim rutaCfdiParcial As String = rutaEntrada & "\XML_PARCIAL\" & archivoIdCFDI & ".xml"
    '        If (File.Exists(rutaCfdiParcial)) Then
    '            xmlCfdi.Load(rutaCfdiParcial)

    '            xmlnsManager = New XmlNamespaceManager(xmlCfdi.NameTable)
    '            'Agregamos los namespaces 
    '            xmlnsManager.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3")
    '            xmlnsManager.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
    '            xmlnsManager.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")


    '            'Valida sellos iguales
    '            If (Me.validaCorrespondenciaSellosBD_XML_Timbre(timbre, xmlCfdi)) Then
    '                Dim root As XmlNode = xmlCfdi.DocumentElement
    '                'Verificamos que el nodo Complementos exista
    '                Dim nodoCompl As XmlNode = root.SelectSingleNode("cfdi:Complemento", xmlnsManager)
    '                If (nodoCompl Is Nothing) Then
    '                    'El nodo Complemento no existe, hay que crearlo
    '                    nodoCompl = xmlCfdi.CreateNode(XmlNodeType.Element, "cfdi", "Complemento", "http://www.sat.gob.mx/cfd/3")
    '                    root.AppendChild(nodoCompl)
    '                End If

    '                Dim nt As NameTable = New NameTable()
    '                Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
    '                nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
    '                Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
    '                Dim xset As XmlReaderSettings = New XmlReaderSettings()
    '                xset.ConformanceLevel = ConformanceLevel.Fragment
    '                Dim rd As XmlReader = XmlReader.Create(New StringReader(timbre), xset, context)
    '                Dim node As XmlNode = xmlCfdi.ReadNode(rd)

    '                '                        nodoCompl.AppendChild(node)
    '                nodoCompl.PrependChild(node)
    '                rd = XmlReader.Create(New StringReader(addenda), xset, context)
    '                Dim node2 As XmlNode = xmlCfdi.ReadNode(rd)
    '                If (node2 IsNot Nothing) Then
    '                    root.AppendChild(node2)
    '                End If
    '                'Guarda el timbre en la BD
    '                If (insertaTimbre) Then
    '                    If Not (insertaTimbreEnBD(node, pResMsg, CInt(archivoIdCFDI), Conexion)) Then
    '                        pResMsg &= "No se pudo insertar en la Base de datos el timbre obtenido" & vbCrLf
    '                    End If
    '                End If


    '            Else
    '                pResMsg &= "No es posible integrar el timbre al CFDI: No hay correspondencia entre los sellos." & vbCrLf
    '                xmlCfdi = Nothing

    '            End If

    '        Else
    '            pResMsg &= "No se encuentra la ruta." & vbCrLf
    '            xmlCfdi = Nothing
    '        End If

    '        rutaCfdiParcial = Nothing

    '    Catch ex As Exception
    '        pResMsg &= ex.Message & vbCrLf
    '        xmlCfdi = Nothing
    '    End Try
    '    integraTimbre = xmlCfdi
    '    xmlCfdi = Nothing

    'End Function
    'Public Function integraTimbreRet(ByVal timbre As String, ByVal rutaEntrada As String, _
    '                              ByVal archivoIdCFDI As String, ByRef pResMsg As String, _
    '                              ByVal addenda As String, ByVal Conexion As String, Optional ByVal insertaTimbre As Boolean = True) As XmlDocument
    '    Dim xmlCfdi As XmlDocument = New XmlDocument()

    '    Dim xmlnsManager As XmlNamespaceManager
    '    Try

    '        Dim rutaCfdiParcial As String = rutaEntrada & "\XML_PARCIAL\" & archivoIdCFDI & ".xml"
    '        If (File.Exists(rutaCfdiParcial)) Then
    '            xmlCfdi.Load(rutaCfdiParcial)

    '            xmlnsManager = New XmlNamespaceManager(xmlCfdi.NameTable)
    '            'Agregamos los namespaces 
    '            xmlnsManager.AddNamespace("retenciones", "http://www.sat.gob.mx/esquemas/retencionpago/1")
    '            xmlnsManager.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")


    '            'Valida sellos iguales
    '            If (Me.validaCorrespondenciaSellosBD_XML_Timbre(timbre, xmlCfdi)) Then
    '                Dim root As XmlNode = xmlCfdi.DocumentElement
    '                'Verificamos que el nodo Complementos exista
    '                Dim nodoCompl As XmlNode = root.SelectSingleNode("retenciones:Complemento", xmlnsManager)
    '                If (nodoCompl Is Nothing) Then
    '                    'El nodo Complemento no existe, hay que crearlo
    '                    nodoCompl = xmlCfdi.CreateNode(XmlNodeType.Element, "retenciones", "Complemento", "http://www.sat.gob.mx/esquemas/retencionpago/1")
    '                    root.AppendChild(nodoCompl)
    '                End If

    '                Dim nt As NameTable = New NameTable()
    '                Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
    '                nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
    '                Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
    '                Dim xset As XmlReaderSettings = New XmlReaderSettings()
    '                xset.ConformanceLevel = ConformanceLevel.Fragment
    '                Dim rd As XmlReader = XmlReader.Create(New StringReader(timbre), xset, context)
    '                Dim node As XmlNode = xmlCfdi.ReadNode(rd)

    '                '                        nodoCompl.AppendChild(node)
    '                nodoCompl.PrependChild(node)
    '                rd = XmlReader.Create(New StringReader(addenda), xset, context)
    '                Dim node2 As XmlNode = xmlCfdi.ReadNode(rd)
    '                If (node2 IsNot Nothing) Then
    '                    root.AppendChild(node2)
    '                End If
    '                'Guarda el timbre en la BD
    '                If (insertaTimbre) Then
    '                    If Not (insertaTimbreEnBD(node, pResMsg, CInt(archivoIdCFDI), Conexion)) Then
    '                        pResMsg &= "No se pudo insertar en la Base de datos el timbre obtenido" & vbCrLf
    '                    End If
    '                End If


    '            Else
    '                pResMsg &= "No es posible integrar el timbre al CFDI: No hay correspondencia entre los sellos." & vbCrLf
    '                xmlCfdi = Nothing

    '            End If

    '        Else
    '            pResMsg &= "No se encuentra la ruta." & vbCrLf
    '            xmlCfdi = Nothing
    '        End If

    '        rutaCfdiParcial = Nothing

    '    Catch ex As Exception
    '        pResMsg &= ex.Message & vbCrLf
    '        xmlCfdi = Nothing
    '    End Try
    '    integraTimbreRet = xmlCfdi
    '    xmlCfdi = Nothing

    'End Function

    Public Function validaCorrespondenciaSellosBD_XML_Timbre(ByVal timbreXML As String, _
                                                                 ByVal pXmlCfdParc As XmlDocument) As Boolean
        Dim selloXml As String = ""
        Dim nodeList As XmlNodeList
        Dim valido As Boolean = False
        Dim nodeListTimbre As XmlNodeList
        Dim xmlTimbre As XmlDocument = New XmlDocument()
        Dim timbre As String = ""
        Dim pResMsg As String = ""

        Try
            Dim nt As NameTable = New NameTable()
            Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
            Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
            Dim xset As XmlReaderSettings = New XmlReaderSettings()
            xset.ConformanceLevel = ConformanceLevel.Fragment
            Dim rd As XmlReader = XmlReader.Create(New StringReader(timbreXML), xset, context)
            Dim node As XmlNode = pXmlCfdParc.ReadNode(rd)

            nodeList = pXmlCfdParc.GetElementsByTagName("cfdi:Comprobante")
            If (nodeList.Count = 0) Then
                nodeList = pXmlCfdParc.GetElementsByTagName("retenciones:Retenciones")
            End If
            timbre = node.Attributes.ItemOf("selloCFD").Value.ToString()
            If (nodeList.Count = 1) Then
                If (nodeList(0).Attributes.ItemOf("sello") Is Nothing) Then
                    selloXml = nodeList(0).Attributes.ItemOf("Sello").Value.ToString()
                Else
                    selloXml = nodeList(0).Attributes.ItemOf("sello").Value.ToString()
                End If
            End If

            If (selloXml.Trim <> "" And timbre.Trim <> "") Then
                If (selloXml = timbre) Then
                    valido = True
                Else
                    valido = False
                End If
            Else
                valido = False
            End If
        Catch ex As Exception
            valido = False
        Finally
            selloXml = Nothing
            nodeList = Nothing
            nodeListTimbre = Nothing
            timbre = Nothing
        End Try
        validaCorrespondenciaSellosBD_XML_Timbre = valido
        valido = Nothing
    End Function

    Public Function nodeNota(ByVal nodo As String, ByRef xml As XmlDocument) As XmlNode
        Try

            Dim nt As NameTable = New NameTable()
            Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
            Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
            Dim xset As XmlReaderSettings = New XmlReaderSettings()
            xset.ConformanceLevel = ConformanceLevel.Fragment
            Dim rd As XmlReader = XmlReader.Create(New StringReader(nodo), xset, context)
            Dim node As XmlNode = xml.ReadNode(rd)

            Return node
        Catch ex As Exception
            Return Nothing
        End Try

    End Function

End Class
